<?php

class Workset_Controller_Action_Helper_Application extends Workset_Controller_Action_Helper_Url {

    const DEF_SORT_FIELD_VAR = 'sidx';
    const DEF_SORT_ORDER_VAR = 'sord';

    function getListId($listId, $req = false) {
        $listId = $this->getList($listId, $req);

        if ($listId) {
            $listId = array_map('intval', $listId);

            foreach ($listId as $key => $value) {
                if ($value <= 0) {
                    unset($listId[$key]);
                }
            }
        }
        return $listId;
    }

    function getList($listId, $req = false) {

        $request = $this->getRequest();

        if (true == $req) {
			$listId = $request->getParam((string)$listId);
		}

        if (!empty($listId)) {
            if (!is_array($listId)) {
                $listId = explode(",", (string)$listId);
            }
            return $listId;
        } else {
            return array();
        }
    }

    function getSortOrder($field = null, $order = null, $defaultField = null, $defaultOrder = null, $req = true) {

        if (true == $req) {
            $request = $this->getRequest();

            if (null === $field) {
                $field = self::DEF_SORT_FIELD_VAR;
            }

            if (null === $order) {
                $order = self::DEF_SORT_ORDER_VAR;
            }

            $field = $request->getParam((string)$field);
            $order = $request->getParam((string)$order);
        }

        if (!$field) {
            if (null === $defaultField) {
                $field = Workset_Model_Object_Abstract::SORT_FIELD;
            } elseif (is_string($defaultField)) {
                $field = $defaultField;
            }
        }

        if (!$order) {
            if (null === $defaultOrder) {
                $order = Workset_Model_Object_Abstract::SORT_ORDER;
            } elseif (is_string($defaultOrder)) {
                $order = $defaultOrder;
            } 
        }

        if ($field && $order) {
            return $field.' '.$order;
        }

        return null;
    }

    function throwException($exception = null, $code = null, $noRender = true) {
        if (true == $noRender) {
            $viewRenderer = Zend_Controller_Action_HelperBroker::getStaticHelper('ViewRenderer');
            $viewRenderer->setNoRender(true);
        }

        if ($exception instanceof Exception) {
            $e = $exception;
        } else {
            $e = new Zend_Exception((string)$exception, $code);
        }

        $this->getResponse()->setException($e);
        return $e;
    }

	function jsFunction($name, $params = array(), $caller = false, $asJsonExpr = false) {
		$func = $this->jsFunctionName();
		$callParams = '';
        $callerParams = array();

		if (is_array($params)) {
			foreach ($params as $key => $value) {
				if (is_string($key)) {
					$params[$key] = $this->jsValue($value);
				} elseif ($caller) {
                    $callerParams[] = $value;
                }
			}
			$callParams = implode(',', $params);
		}

		$js = $func.'.'.$name.'('.$callParams.');';
		if ($caller == true) {
            $callerParams = implode(',', $callerParams);
			$js = 'function('.$callerParams.') { return '.$js.' }';
		}

        if ($asJsonExpr == true) {
            return new Zend_Json_Expr($js);
        } else {
            return $js;
        }
	}

	function jsValue($value) {
		switch ($value) {
			case is_string($value) && (string)(int)$value !== $value:
				$value = '"'.addslashes($value).'"';
			break;

			case null === $value:
				$value = 'null';
			break;

			case is_array($value):
				$value = Zend_Json::encode($value, true);
			break;

			case is_bool($value):
				$value = $value ? 'true' : 'false';
			break;
		}

		return $value;
	}

	function jsFunctionName() {
		$action = $this->getRequest()->getActionName();
		return preg_replace("/[\-\.]/", "", $action);
	}

    /**
     * @deprecated
     * @see Application_Action_Helper_FileTransfer
     * @param  $path
     * @return array|Workset_Model_Exception
     */
    function uploadFiles($path = null) {

        if (null === $path) {
            $path = UPLOAD_FILE_PATH;
        }

        $uploader = new Workset_File_Transfer_Adapter_Http();
        $uploader->setDestination(array($path, $this->getRequest()->getModuleName()));

        if (!$uploader->receive()) {
            $messages = $uploader->getMessages();
            $messages = implode('\n\r', $messages);
            return $this->throwException($messages, 500);
        }

        $fileinfo = $uploader->getFileInfo();

        foreach ($fileinfo as $key => $content) {
            if ($content['received'] != true) {
                unset($fileinfo[$key]);
                continue;
            }

            $utils = Zend_Controller_Action_HelperBroker::getStaticHelper('Utils');
            $params = $utils->params(array(
                 time() => uniqid(),
                'name' => $content['name'],
                'type' => $content['type'],
                'path' => $content['destination'],
                'size' => $content['size']
            ));

            $fileinfo[$key] = $params;
        }

        return $fileinfo;
    }

	function redirectToBackUrl($sBackUrl = null) {
		$req = $this->getRequest();
		$resp = $this->getResponse();
		$action = $this->getActionController();

		if (!$sBackUrl) {
			if ($sBackUrl = $req->getParam('backurl')) {
				$sBackUrl = $action->getHelper('httpUri')->direct($sBackUrl);
			}
			else {
				$sBackUrl = strpos($_SERVER['HTTP_REFERER'], parse_url('http://' . $req->getHttpHost() . $_SERVER['REQUEST_URI'], PHP_URL_PATH)) >= 0
						? 'http://' . $this->_request->getHttpHost() . '/'
						: $_SERVER['HTTP_REFERER'];
			}
		}

		$resp->setRedirect($sBackUrl,302);
	}

}

?>